﻿using System;
using NHibernate;

namespace ProcelNasEscolas.Data
{
    public class SessionManager
    {       
        [ThreadStatic]
        private static ISession session;
        private static ISessionFactory sessionFactory = null;
        private static object locker = new object();
        private static ITransaction transaction;
      
        public static void Init()
        {
            sessionFactory = CreateSessionFactory();
        }

        public static void SetSessionFactory(ISessionFactory sessionfactory)
        {
            sessionFactory = sessionfactory;
        }
        
        private static ISessionFactory GetSessionFactory()
        {
            if (sessionFactory == null)
            {
                lock (locker)
                {
                    if (sessionFactory == null)
                    {
                        sessionFactory = CreateSessionFactory();
                    }
                }
            }
            return sessionFactory;
        }

        public static ISession GetSession()
        {
            if (session == null)
            {
                session = GetSessionFactory().OpenSession();
                transaction = session.BeginTransaction();
            }
            return session;
        }

        public static void CloseSession()
        {
            if (session != null && session.IsOpen)
            {
                try
                {
                    transaction.Commit();
                }
                catch (Exception a)
                {
                    a.HelpLink = "aa";
                }
                finally
                {
                    try
                    {
                        session.Close();
                    }
                    catch (Exception a)
                    {
                        a.HelpLink = "aa";
                    }
                }
            }
            session = null;
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return AutoMappingConfiguration.CreateConfiguration();
        }
    }
}
